package com.mrx.commons.mail;

import com.mrx.commons.mail.model.MailDTO;
import com.mrx.commons.mail.model.XMailProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.util.Date;
import java.util.regex.Pattern;

/**
 * @author Mr.X
 * @since 2024-01-12 09:31
 **/
@EnableConfigurationProperties(XMailProperties.class)
public class MailHelper {

    @Resource
    private JavaMailSender javaMailSender;
    @Resource
    private XMailProperties mailProperties;

    private static final Pattern pattern = Pattern.compile("^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$");
    private static final Logger logger = LoggerFactory.getLogger(MailHelper.class);

    public void sendSimpleMail(MailDTO mailDTO) {
        if (!mailProperties.getRealSend()) {
            logger.debug("spring.mail.real 为 false, 不发送邮件, 邮件内容为: {}", mailDTO);
            return;
        }
        checkMail(mailDTO);
        Assert.isTrue(pattern.matcher(mailDTO.getSendTo()).find(), "收件人信息有误");
        SimpleMailMessage message = new SimpleMailMessage();
        // 邮件发件人
        message.setFrom(mailProperties.getUsername());
        // 邮件收件人 1或多个
        message.setTo(mailDTO.getSendTo().split(","));
        // 邮件主题
        message.setSubject(mailDTO.getSubject());
        // 邮件内容
        message.setText(mailDTO.getText());
        // 邮件发送时间
        message.setSentDate(new Date());
        javaMailSender.send(message);
        logger.info("发送邮件成功: {} -> {}", mailProperties.getUsername(), mailDTO.getSendTo());
    }

    private void checkMail(MailDTO mailDTO) {
        Assert.notNull(mailDTO, "邮件请求不能为空");
        Assert.notNull(mailDTO.getSendTo(), "邮件收件人不能为空");
        Assert.notNull(mailDTO.getSubject(), "邮件主题不能为空");
        Assert.notNull(mailDTO.getText(), "邮件内容不能为空");
    }

}
